<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Wxpay extends CI_Controller
{
    protected $key;

    public function __construct()
    {
        parent::__construct();
        $this->key = IOSS_StaticConfig::$PayKey;
    }


    /**
     * 支付成功回调
     * @return bool|string
     */
    public function notify(){
        $postXml = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信参数
        if (empty($postXml)) {
            return false;
        }
        $return = array();
        //XML转数组
        $attr = $this->xmlToArray($postXml);
        //获取签名
        $sign = $attr['sign'];
        unset($attr['sign']);
        $xcx_sign = $this->getSign($attr);
        if ($sign !== $xcx_sign){
            $return['return_code'] = 'FAIL';
            $return['return_msg	'] = '签名错误';
        }else{
            $result = IOSS_StaticConfig::receive_notify($attr);
            if (!$result){
                //微信通知支付成功
                if ($attr['result_code'] == 'SUCCESS'){
                    //处理订单
                    $code = IOSS_StaticConfig::check_order($attr['out_trade_no'],$attr['cash_fee']/100);
                    if ($code){
                        //返回微信参数
                        $return['return_code'] = 'SUCCESS';
                        $return['return_msg	'] = 'OK';
                    }
                }
            }

        }
        return $this->arrayToXml($return);
    }

    //数组转换成xml
    private function arrayToXml($arr) {
        $xml = "<root>";
        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $xml .= "<" . $key . ">" . $this->arrayToXml($val) . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }
        }
        $xml .= "</root>";
        return $xml;
    }

    //xml转换成数组
    private function xmlToArray($xml) {


        //禁止引用外部xml实体

        libxml_disable_entity_loader(true);


        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);


        $val = json_decode(json_encode($xmlstring), true);


        return $val;
    }

    //作用：产生随机字符串，不长于32位
    private function createNoncestr($length = 32) {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    //作用：生成签名
    public function getSign($Obj) {
        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        var_dump($String);
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . $this->key;
        //签名步骤三：MD5加密
        var_dump($String);
        $String = md5($String);
        var_dump($String);
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        var_dump($String);
        return $result_;
    }

    ///作用：格式化参数，签名过程需要使用
    private function formatBizQueryParaMap($paraMap, $urlencode) {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }

        if (strlen($buff) > 0){
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }else{
            $reqPar = "";
        }
        return $reqPar;
    }

}
